<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Common\Enum\{Attributes, ResultMsg, Http, Header, TrueCode,Prefix};
use App\Common\Helper;
use App\Services\Admin\Role;
use App\Services\Info\TraitUse;
use App\Models\Mysql\Orm\Lsv\Admins;
use App\Common\Http\Basics\Auth;

class AdminCheckApiAuth
{
    use TraitUse;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $path =  $request->header(Header::ADMIN_ROUTER_PATH->value, null);
        /* 没有传路径上来 */
        if (!$path) return Helper::toHttpEnum(Auth::ADMINS_ROUTER_PATH_NOT_DEFINED);
        $role_id = $this->getSetInfoReq($request,Attributes::LOGIN_INFO,'admins_id',Admins::class,['role_id'])['role_id'];
        $url = explode('/',$request->path());
        if(\AppRouter::ADMIN_API->prefix() !== "" && \AppRouter::ADMIN_API->prefix()  === $url[0]) array_shift($url);
        $menuApi = Role::checkMenuApi((int)$role_id,(string)implode('/',$url));
        if($menuApi === null )  return $next($request);  //没有设置权限的接口放行
        if($menuApi['check'] === false ) return Helper::toHttpEnum(Auth::NOT_AUTH);
        else {
            //有API权限时放行
            $request->attributes->add([Attributes::AUTH_NAME->value => $menuApi['auth_name']]);  //保存当前的权限文字
            $request->attributes->add([Attributes::MENU_TITLE->value => $menuApi['menu_title']]);     //当前栏目名称
            $request->attributes->add([Attributes::ADD_LOG->value => $menuApi['add_log']]);      //是否加入日志
            return $next($request);
        }
    }
}
